<?php

namespace addons\yungift\model;

use addons\yungift\library\ModelTrait;
use addons\yungift\library\Super;
use think\Model;
use traits\model\SoftDelete;

/**
 * 礼品 - 券码
 */
class GiftCode extends Model
{
    use ModelTrait;
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'yungift_gift_code';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = 'deleted_at';
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    // 不显示的字段
    protected $hidden = ['deleted_at'];

    protected $resultSetType = 'collection';

    // 自定义初始化
    protected static function init()
    {
        GiftSpec::event('before_write', function ($item) {
            return true;
        });
    }

    public function giftData()
    {
        return $this->belongsTo(GiftMain::class, 'gift_id', 'id');
    }

    public function giftSpecData()
    {
        return $this->belongsTo(GiftSpec::class, 'gift_spec_id', 'id');
    }

    public function scopeShow($query)
    {
        return $query->where('status', '=', self::STATUS_NORMAL);
    }

    // 状态
    const STATUS_NORMAL = 1;
    const STATUS_GAINED = 2;
    const STATUS_HIDDEN = 3;

    public static function getStatusList()
    {
        return [self::STATUS_NORMAL => __('未领取'), self::STATUS_GAINED => __('已领取'), self::STATUS_HIDDEN => __('屏蔽')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $optionList = self::getStatusList();

        return $optionList[$data['status']] ?? $data['status'];
    }

    public function getDataMixAttr($value, $data)
    {
        return Super::stringHide($data['data']);
    }
}
